package com.butnet.myframe.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.butnet.myframe.ajax.AjaxParameter;

public class DirServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doDir(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doDir(req, resp);
	}

	private void doDir(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String uri = req.getRequestURI();
		uri = uri.replaceAll("//", "/");
		String path = uri.substring(getServletContext().getContextPath().length());
		path = path.substring(req.getServletPath().length());
		path = AjaxParameter.ajaxToURL(path);
		System.out.println("DirSerlvet[" + req.getServletPath() + "]: path=" + path);
		
		resp.setCharacterEncoding("UTF-8");
		String file = this.getInitParameter("file");
		if (file == null) {
			resp.getWriter().println("参数file不存在");
		} else {
			File f = new File(file, path);
			if (f.isFile()) {
				FileServlet.doFile(f, req, resp);
			} else {
				File[] fs = f.listFiles();
				resp.setContentType("text/html");
				PrintWriter w = resp.getWriter();
				w.println("<html><head><title>" + f.getName() + "</title></head><body>");
				w.println("<table><tr><td>文件名</td><td>文件/目录</td><td>大小</td></tr>");
				if (fs != null) {
					for (File t : fs) {
						w.println("<tr><td><a href=\"" + getServletContext().getContextPath() + req.getServletPath() +path+"/"+ t.getName() + "\">" + t.getName() + "</a></td><td>"+(t.isFile()?"文件":"目录")+"</td><td>" + t.length() + "</td></tr>");
					}
				} else {
					w.println("<tr><td colspan=\"3\">空</td></tr>");
				}
				w.println("</table></body></html>");
				w.close();
			}
		}
	}
}
